import createG2 from 'g2-react';
import { Stat } from 'g2';
import React from 'react';
import G2 from 'g2';     //G2要引入，坑死了，大爷的
import ReactDOM from 'react-dom';
import { DatePicker,Modal} from 'antd';
import ReportTable from 'components/ReportTables/HistoryTable';//引入报表表格
import TWIcon from "components/TWIcon/index";
import moment from 'moment';
import ajax from '../../../utils/ajax';
import './index.less';
import LineChart from '../../Charts/history/LineChart';//引入线型图
import PieChart from '../../Charts/history/PieChart';//引入饼型图
import TestBarChart from '../../Charts/history/TestBarChart';//引入条形图


const { MonthPicker, RangePicker } = DatePicker;
const confirm = Modal.confirm;
const thirtyDays=30*24*60*60*1000;//定义一个30天常量
const day='';
const startDay='';
const stopDay='';
const Frame = G2.Frame;
let frame;


function showdate(n){//得到日期前29天日期
  var date = new Date(new Date()-0+n*86400000);
  var result=""+date.getFullYear();
  var month=date.getMonth()+1;
  var day=date.getDate();
  if((month)<10){
     result=result+"0"+(month);
  }else{
    result=result+""+(month);
  }
  if(date.getDate()<10){
     result=result+"0"+ day;
  }else{
    result=result+""+ day;
  }
  return result;
} 

/**
 * 开始时间不能大于现在时间
 */
function disabledDate(current) {
  return current && current.valueOf() > Date.now();
}

/**
 * 报表
 */
class HistoryChartReport extends React.Component {

  constructor(props) {
    super(props);
    this.initData();
    this.initUserData(day);
    this.initMuseumData(startDay,stopDay);
    this.initTableData(startDay,stopDay);
  }

  state = {
     open:false,//控制日期控件开闭
     visible: false,//控制警告控件开闭
     //totalData:[],//总预约数据
     userData:[],//用户每日入场数据
     museumData:[],//范围时间内场馆预约数据
    // reportData:[],//范围时间内场馆预约表单数据
     userTotalCount:0,//用户累计入场次数
  };

  //初始化页面预约人次请求
  initData() {
    var self = this;
    const paramData={};
    paramData.day= new Date().format('yyyyMMdd');
    const url = '/statistic/getMuseumAppointmentedPersonCountStatistic';
    ajax.post({
      url: url,
      async: false,//必须用同步请求，否则数据显示异常
      params:paramData,
      success: function (res) {
        self.state.totalData=res.data;
      }
    })
   }

  //初始化用户每日入场请求
  initUserData(day){
     var self = this;
     const paramData={};
     if(day){
        paramData.day=day;
     }else{
        paramData.day= new Date().format('yyyyMMdd');
     }
     const url = '/statistic/getMuseumIntoTimeInfoByGiveDay';
     ajax.post({
      url: url,
      async: true,
      params:paramData,
      success: function (res) {
        if(!res.data.isCloseDay){
           self.setState({userData:res.data.data});//必须要这样传值，否则子组件无法响应值改变
           self.state.userTotalCount=res.data.totalCount;
        }
      }
     })
   }

  //初始化场馆预约请求
 initMuseumData(startDay,stopDay){
    var self = this;
    const paramData={};
    if(startDay&&stopDay){
      paramData.startDay=startDay;
      paramData.stopDay=stopDay;
    }else{
      paramData.startDay=showdate(-29);
      paramData.stopDay=new Date().format('yyyyMMdd');
    }
    const url = '/statistic/getMuseumAllAppointmentInfoByStartDayAndStopDay';
    ajax.post({
       url: url,
       params:paramData,
       async:true,
       success: function (res) {
          self.setState({museumData:res.data});
          var tmpData=[];
          for(var i=0;i<res.data.data.length;i++){
              tmpData.push(res.data.data[i]);
          }
          frame=new Frame(tmpData);
          frame = Frame.combinColumns(frame,['totalCount','validCount'],'count', 'number', 'simpleDayStr','day');
          frame.addCol('type', function(obj) {
               var key = obj.number;
               var type;
               if (key === 'totalCount'||key === 'validCount') {
                    type = 'a';
               } else {
                    type = 'b';
               }
               return type;
          });
          self.setState({frameData:frame});
          console.log(self.state.frameData);
       }
     })
  }

  //初始化表格数据
  initTableData(startDay,stopDay){
    var self = this;
    const paramData={};
    if(startDay&&stopDay){
      paramData.startDay=startDay;
      paramData.stopDay=stopDay;
    }else{
      paramData.startDay=showdate(-29);
      paramData.stopDay=new Date().format('yyyyMMdd');
    }
    const url = '/statistic/getMuseumSuccessOrdersInfoByStartDayAndStopDay';
    ajax.post({
      url: url,
      async: true,
      params:paramData,
      success: function (res) {
        var tmpData=[];
        for(var i=0;i<res.data.length;i++){
            var tmp={};
            tmp.key=i+1;
            tmp.appointmentOrderTypeStr=res.data[i].appointmentOrderTypeStr;
            tmp.type=res.data[i].type;
            tmp.totalPrice=res.data[i].totalPrice;
            tmp.disparkSeasonInfo=res.data[i].disparkSeasonInfo;
            tmp.appointmentPersonInfo=res.data[i].appointmentPersonInfo;
            tmp.appointmentContactsStr=res.data[i].appointmentContactsStr;
            tmpData.push(tmp);
        }
        self.setState({reportData:tmpData});
      }
    })
  }

  /**
   * 时间改变发生事件
   */
  onEndChange = (value) =>{
     var day=new Date(value).format('yyyyMMdd');
     if(day){//day必须有值才可以
        this.initUserData(day);//重新处理请求
     }
  }

  /**
   * 判断时间间隔不能超过30天
   */
  onRangeTime=(value)=>{
      //得到开始时间和结束时间
      var startDay=new Date(value[0]);
      var stopDay=new Date(value[1]);
      var tmpDate=stopDay-startDay;
      if(tmpDate>thirtyDays){
         this.setState({open: true});//日期对话框不能关闭
         this.showConfirm();
      }else{
        startDay=startDay.format('yyyyMMdd');
        stopDay=stopDay.format('yyyyMMdd');
        this.setState({open: false});
        this.initMuseumData(startDay,stopDay);//重新处理请求
        this.initTableData(startDay,stopDay);
      }
  }

  /**
  * 定义警告对话框
  */
  showConfirm() {
     var _this=this;
     confirm({
        title: '警告',
        content: '最多选择30天日期，请重新选择！',
        onOk() {
           _this.setState({open: true});//警告对话框，点击确认时不能把时间对话框关闭
        },
        onCancel() {
            _this.setState({open: true});//警告对话框，点击取消时时不能把时间对话框关闭
         },
     });
  }

  render() {
    return (
      <div>
        <div className="container">
            <div className="container-1">
                    <div className="ant-history-img">
                       <TWIcon type="lishizong-"/>
                    </div>
                    <div className="ant-history">
                        <label className="ant-history-title">历史总预约人次</label>
                        <br/>
                        <label className="ant-history-number" >{this.state.totalData[0].count}</label>
                    </div>
            </div>
            <div className="container-2">
                    <div className="ant-history-img">
                       <TWIcon type="jinbannian-"/>
                    </div>
                    <div className="ant-history">
                        <label className="ant-history-title">近半年预约人次</label>
                        <br/>
                        <label className="ant-history-number" >{this.state.totalData[1].count}</label>
                    </div>
            </div>
            <div className="container-3">
                    <div className="ant-history-img">
                        <TWIcon type="benyue-"/>
                    </div>
                    <div className="ant-history">
                        <label className="ant-history-title">本月预约人次</label>
                        <br/>
                        <label className="ant-history-number" >{this.state.totalData[2].count}</label>
                    </div>
            </div>
            <div className="container-4">
                    <div className="ant-history-img">
                        <TWIcon type="benzhou-"/>
                    </div>
                    <div className="ant-history">
                        <label className="ant-history-title">本周预约人次</label>
                        <br/>
                        <label className="ant-history-number" >{this.state.totalData[3].count}</label>
                    </div>
            </div>
        </div>  
        <div className="ant-chart-container-1">
                 <div className="ant-chart-line">
                     <div className="ant-chart-line-title">用户每日入场时间段概览</div>
                     <div className="ant-chart-line-title-1">
                     <label>累计入场人次：{this.state.userTotalCount}</label>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                     <span className="ant-chart-span">选择日期：
                         <DatePicker 
                            onChange={this.onEndChange} disabledDate={disabledDate}
                            showToday defaultValue={moment(new Date(), "YYYY-MM-DD")} format="YYYY-MM-DD"
                         />
                     </span>
                     </div>
                     <LineChart userData={this.state.userData}/>
                 </div>
                 <div className="ant-chart-pie">
                     <div className="ant-chart-pie-title">用户每日入场时间占比情况</div>
                     <br/>
                     <label></label>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                     <span className="ant-chart-span"></span>
                     <PieChart userData={this.state.userData}/>
                 </div>
        </div>
        <div className="ant-chart-container-2">
            <div className="ant-chart-container2-title">
                <label className="ant-chart-container2-title-text">范围时间内场馆预约情况</label>
                <span className="ant-chart-container2-title-date">选择日期：
                    <RangePicker 
                       disabledDate={disabledDate} 
                       format="YYYY-MM-DD HH:mm:ss" size={'Large'}
                       onChange={this.onRangeTime}
                       open={this.state.open}
                    />
               </span>
            </div>
            <div className="ant-chart-box">  
                <label className="ant-chart-box-title">累计开放位置</label>
                <br/>
                <label className="ant-chart-box-number">{this.state.museumData.totalCount}</label>
                <br/>
                <br/>
                <label className="ant-chart-box-title">累计预约人次</label>
                <br/>
                <label className="ant-chart-box-number">{this.state.museumData.totalValidCount}</label>
                <br/>
                <br/>
                <label className="ant-chart-box-title">总体预约率</label>
                <br/>
                <label className="ant-chart-box-number">{this.state.museumData.averageProportion}%</label>
            </div>
            <div className="ant-chart-bar">
                <label className="ant-chart-bar-title">场馆预约率</label>
                <br/>
                <label className="ant-chart-bar-title-1" >平均预约率：{this.state.museumData.proportion}%</label>
            </div>
        </div>
        <div className="ant-chart-container-3">
             <ReportTable reportData={this.state.reportData}/>
        </div>
      </div>
    );
  }

}
export default HistoryChartReport;